/*
 * Copyright 2007-2009 the original author or authors.
 *
 * Licensed under the Apache License, Version 2.0 (the "License");
 * you may not use this file except in compliance with the License.
 * You may obtain a copy of the License at
 *
 *      http://www.apache.org/licenses/LICENSE-2.0
 *
 * Unless required by applicable law or agreed to in writing, software
 * distributed under the License is distributed on an "AS IS" BASIS,
 * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
 * See the License for the specific language governing permissions and
 * limitations under the License. 
 * 
 * Project: gtinyurl
 */
package org.gnut.tinyurl.portlet.contextprovider.pluto;

import java.lang.reflect.Method;

import javax.servlet.ServletContext;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;

/**
 * 
 * @author tungt
 * 
 */
public class PlutoServletContextProviderUtils {
	/**
	 * 
	 * @param clazz
	 * @param methodName
	 * @param params
	 * @return
	 * @throws Exception
	 */
	public static Method searchMethod(Class clazz, String methodName,
			Class[] params) throws Exception {
		if (clazz.getSuperclass() != null) {
			try {
				Method methods = clazz.getDeclaredMethod(methodName, params);
				if (methods != null)
					return methods;
			} catch (Exception e) {
			}
			return searchMethod(clazz.getSuperclass(), methodName, params);
		} else {
			Method methods = clazz.getDeclaredMethod(methodName, params);
			return methods;
		}
	}

	/**
	 * 
	 * @param object
	 * @return
	 * @throws Exception
	 */
	public static HttpServletRequest getHttpServletRequest(Object object)
			throws Exception {
		Method method = searchMethod(object.getClass(), "getServletRequest",
				new Class[] {});
		if (method != null) {
			method.setAccessible(true);
			return (HttpServletRequest) method.invoke(object, new Object[] {});
		}
		throw new Exception("Can't create request");
	}

	/**
	 * 
	 * @param object
	 * @return
	 * @throws Exception
	 */
	public static HttpServletResponse getHttpServletResponse(Object object)
			throws Exception {
		Method method = searchMethod(object.getClass(), "getServletResponse",
				new Class[] {});
		if (method != null) {
			method.setAccessible(true);
			return (HttpServletResponse) method.invoke(object, new Object[] {});
		}
		throw new Exception("Can't create reponse");
	}

	/**
	 * 
	 * @param object
	 * @return
	 * @throws Exception
	 */
	public static ServletContext getServletContext(Object object)
			throws Exception {
		Method method = searchMethod(object.getClass(), "getServletContext",
				new Class[] {});
		if (method != null) {
			method.setAccessible(true);
			return (ServletContext) method.invoke(object, new Object[] {});
		}
		throw new Exception("Can't create Servlet Context");
	}

}
